package com.gyc.simple.sysuser.config.shiro;

import com.gyc.simple.sysuser.entity.base.ISource;
import com.gyc.simple.sysuser.entity.base.IUser;
import com.gyc.simple.sysuser.service.SysResourceService;
import com.gyc.simple.sysuser.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysResourceService sysResourceService;

    public ShiroRealm(CredentialsMatcher matcher) {
        super(matcher);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        IUser iUser = (IUser) SecurityUtils.getSubject().getPrincipal();
        List<ISource> iSources = sysResourceService.selectByUID(iUser.getIuId());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (int i=0;i<iSources.size();i++){
            simpleAuthorizationInfo.addStringPermission(iSources.get(i).getIsourceurl());
        }
        return simpleAuthorizationInfo;
    }


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        IUser user = sysUserService.selectByName(userName);
        if(user==null) throw new UnknownAccountException();
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,user.getIuPassword(),getName());
        return simpleAuthenticationInfo;
    }
}
